package com.Sing.Controller;

import com.Sing.Pojo.Book;
import com.Sing.Pojo.Type;
import com.Sing.Service.BookServiceImpl;
import com.Sing.Service.TypeServiceImpl;
import com.Sing.Utils.Constant;
import com.mysql.cj.util.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class BookController {

    private BookServiceImpl bookService;
    @Autowired
    @Qualifier("bookServiceImpl")
    public void setBookService(BookServiceImpl bookService) {
        this.bookService = bookService;
    }
    private TypeServiceImpl typeService;
    @Autowired
    @Qualifier("typeServiceImpl")
    public void setTypeService(TypeServiceImpl typeService) {
        this.typeService = typeService;
    }

    // 跳转至 bookIndex 的界面
    @RequestMapping( "/bookIndex" )
    public String bookIndexJump(){

        return "/book/bookIndex";
    }

    // 查询 Book 表中的所有数据
    @RequestMapping("/findAllList")
    @ResponseBody
    public ArrayList<Type> findAllList(){

        return typeService.getAllData();
    }

    // 查询 Book 表中的所有符合条件的数据
    @RequestMapping("/bookAll")
    @ResponseBody
    public HashMap<String,Object> bookIndex( String limit, String page,
                                             String name, String isbn, String typeId ){

        HashMap<String, Object> resultMap = new HashMap<>();
        int typeIdTemp = 0;
        int pageSize = 0, pageContext = 0;

        pageSize = Integer.parseInt( limit );
        pageContext = ( Integer.parseInt( page ) - 1 ) * pageSize;

        System.out.println( pageSize + pageContext );

        if ( name == null || name.equals("") ){
            name = null;
        } else {
            name = "%" + name + "%";
        }

        if ( StringUtils.isNullOrEmpty( isbn ) ){
            isbn = null;
        } else {
            isbn = "%" + isbn + "%";
        }

        if ( typeId == null || typeId.equals("") ){
            typeId = null;
        } else {
            typeIdTemp = Integer.parseInt( typeId );
        }

        ArrayList<Book> bookArrayList = bookService.getData( pageContext, pageSize, name, isbn, typeId );
        int dataCount = bookService.getDataCount(name, isbn, typeId);

        resultMap.put( "data", bookArrayList );
        resultMap.put("code", 0);
        resultMap.put( "count", dataCount );

        return resultMap;
    }

    // 根据 ID 查询 Book 表数据
    @RequestMapping("/queryBookInfoById")
    public String queryBookInfoById( String id, HttpServletRequest req, Model model ){
        Book book = bookService.queryBookById( Integer.parseInt( id ) );

        req.getSession().setAttribute( Constant.BookId, id );
        model.addAttribute( "info", book );

        return "book/updateBook";
    }

    // 更新修改 Book 表中的数据
    @RequestMapping("/updateBookSubmit")
    @ResponseBody
    public HashMap<String,Object> updateBookSubmit( @RequestBody(required = false) Book book, HttpServletRequest req ){
        HashMap<String, Object> resultMap = new HashMap<>();
        HashMap<String, Object> paramMap = new HashMap<>();

        String temp = (String) req.getSession().getAttribute( Constant.BookId );
        int bookId = Integer.parseInt( temp );
        // 清除 Session
        req.getSession().removeAttribute( Constant.BookId );

        paramMap.put( "modifyId", bookId );
        paramMap.put( "name", book.getName() );
        paramMap.put( "isbn", book.getIsbn() );
        paramMap.put( "author", book.getAuthor() );
        paramMap.put( "publish", book.getPublish() );
        paramMap.put( "language", book.getLanguage() );
        paramMap.put( "price", book.getPrice() );
        paramMap.put( "introduction", book.getIntroduction() );
        paramMap.put( "type_id", book.getTypeId() );
        paramMap.put( "publish_date", book.getPublishDate() );

        boolean flag = bookService.modifyData( paramMap );

        if ( flag ){
            resultMap.put( "code", 0 );
        }

        return resultMap;
    }

    // 跳转到图书添加的页面
    @RequestMapping("/bookAdd")
    public String bookAddJump(){
        return "book/bookAdd";
    }

    // 提交对 Book 表的添加
    @RequestMapping("/addBookSubmit")
    @ResponseBody
    public HashMap<Object,Object> addBookSubmit( @RequestBody Book book ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // 设置 Book 的 ID 为当前数据的总量 + 1
        book.setId( bookService.getDataCount( null, null, null ) + 1 );

        // 设置借出状态，默认为 未借出
        book.setStatus( 0 );

        // 若取不到 JS 页面中的时间，就赋予一个随机时间
        if ( book.getPublishDate() == null ){
            book.setPublishDate( getRandomDate() );
        }

        if ( bookService.addBook( book ) ){
            resultMap.put( "code", "0" );
        } else {
            resultMap.put( "msg", "添加失败" );
        }

        return resultMap;
    }

    // 删除表数据
    @RequestMapping("/deleteBook")
    @ResponseBody
    public HashMap<Object,Object> deleteBook( String ids ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // ids 有q可能是一个字符串，因此将其拆分为数组，挨个遍历删除
        boolean flag = true;
        String[] tempIds = ids.split(",");
        for ( String temp : tempIds ){
            // 将拆分出的数据转换为 Integer 型的数据，再进行删除
            int Id = Integer.parseInt( temp );
            // 如果删除失败，结束执行
            if ( ! bookService.deleteBook( Id ) ){
                flag = false;
                break;
            }
        }

        if ( flag ){
            resultMap.put( "code", 0 );
        }

        return resultMap;
    }

    // 生成随机时间
    public Date getRandomDate() {

        Random random = new Random();

        // 获取当前年份
        Calendar calendar = Calendar.getInstance();
        int tempYear = calendar.get(Calendar.YEAR) - 1500;

        // 生成年月日
        String year = String.valueOf( Math.abs(random.nextInt() % tempYear) + 1500 );
        String month = String.valueOf( Math.abs(random.nextInt() % 11) + 1 );
        if ( month.length() < 2 ){
            month = "0" + month;
        }
        String day = String.valueOf( Math.abs(random.nextInt() % 29) + 1 );
        if ( day.length() < 2 ){
            day = "0" + day;
        }

        // 生成时间
        String dateString = year + "-" + month + "-" + day + " : 00:00:00";
        SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd : HH:mm:ss" );

        try {
            return dateFormat.parse( dateString );
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
